<?php
class Application_Model_CategoryMapper extends Application_Model_Mapper
{
  protected $_dbTableClass = "Application_Model_DbTable_Category";
  protected $_model = "Application_Model_Category";

  public function save(Application_Model_Base $obj)
  {
    $pk = $obj->getPrimaryKey();
    $options = $obj->getOptions();
    unset($options['time']);
    if (!($id = $obj->get($pk))) {
      return $this->getDbTable()->insert($options);
    } 
    else {
      $data = $options;
      unset($data[$pk]);
      return $this->getDbTable()->update($data, "$pk = $id");
    }
  }

  /* 
   * get sub categories of cat_id
   * param
   * cat_id the parent category id
   */
  public function getCategoryList($cat_id)
  {
    $results = $this->fetchAll("parent = ".$cat_id);
    $categories = array();
    foreach($results as $cat)
      {
	$categories[$cat->get("id")] = $cat->get("name");
      }
    return $categories;
  }


  /* get the crumb code of the given category id 
   * example: 
   * 首页 > 计算机 > 编程语言(act_id given)  
   */
  public function crumbAction($cat_id)
  {
    /* $mapper = new Application_Model_CategoryMapper(); */

    $crumbs = array();
    while ($cat_id)
      {
	$cat = new Application_Model_Category();
	$this->find($cat_id, $cat);

	$crumbs[] = $cat;
	$cat_id = $cat->get("parent");
      }

    return array_reverse($crumbs);
  }

  /* 
   * 返回分类的路径
   * 如 计算机 》 编程语言 》 C
   * 返回值：
Array
(
    [0] => Array
        (
            [select] => Application_Model_Category Object
                (
                    [data:protected] => Array
                        (
                            [id] => 11
                            [parent] => 0
                            [name] => 外语
                            [time] => 
                        )

                    [primary_key_name:protected] => id
                )

            [categories] => Array
                (
                    [9] => 财务
                    [10] => 计算机
                    [11] => 外语
                    [12] => 金融
                    [64] => 设计
                    [63] => 工程
                    [62] => 建筑
                )

        )

	)
   */
  public function categoryPathAction($cat_id)
  {
    /* $mapper = new Application_Model_CategoryMapper(); */

    $path = array();
    while ($cat_id)
      {
	$cat = new Application_Model_Category();
	$this->find($cat_id, $cat);
	if (isset($cat) && $cat->get("id"))
	  {
	    $cat_id = $cat->get("parent");
	    $cats = $this->getCategoryList($cat_id);
	    $path[] = array("select"=>$cat, "categories"=>$cats);
	  }
	else
	  break;
      }

    return array_reverse($path);
  }

  public function getSubCategory($cat_id)
  {
    return $this->fetchAll("parent = $cat_id");
  }
  public function getAllSubCategory($cat_id)
  {
    $res = array();
    /* input it's self */
    $cat = new Application_Model_Category();
    $this->find($cat_id, $cat);
    $res[] = $cat;

    $sub_cats = $this->getSubCategory($cat_id);
    if (isset($sub_cats) && !empty($sub_cats))
	    foreach($sub_cats as $id=>$cat)
	    {
		    $res[] = $cat;
		    $r = $this->getAllSubCategory($cat->get("id"));
		    if (isset($r) && !empty($r))
			    $res = array_merge($res, $r);
	    }

    $result = array();
    // sort the result as an array
    if (isset($res) && count($res) >0)
      foreach($res as $cat)
	{
	  $result[$cat->get("id")] = $cat;
	}

    return $result;
  }

  /* 获取每一个类别课程播放的总次数 
   * return array ($cat_id=>$play_times, $cat_id2=>$play_times2, ...) or null
   * 
   **/
  public function getCategoryPlayTimes()
  {
    $db = $this->getDbTable()->getAdapter();
    $select = $db->select();
    $select->from(array("cat"=>"category"), array("cat.name","cid"=>"cat.id", "times"=>"count(v.id)"))
      ->join(array("c"=>"content"), "cat.id = c.cat_id")
      ->join(array("v"=>"view_history"), "c.id = v.cont_id")
      ->group("cat.id")
      ->order("times desc");
    $cats_play_info = $db->fetchAll($select);
    if (!isset($cats_play_info) || empty($cats_play_info))
      return null;

    $res = array();
    foreach($cats_play_info as $info)
      {
	$res[$info["cid"]] = $info["times"];
      }
    return $res;
  }
  /* 
   * 从一个类别路径中获取最终的类别,类别从大到小依次是：
   * cat_id_0, cat_id_1, cat_id_2, cat_id_3, cat_id_4
   * 如, 计算机 》 编程语言 》 C
   * 获得的是类别C的id
   */
  static function getLastCatId(&$post)
  {
    $i = 4;
    /* print "getLastCatId<br/>"; */
    while ($i >= 0)
      {
	/* print "$i <br/>"; */
	if (isset($post["cat_id_$i"]) && !empty($post["cat_id_$i"]))
	  return $post["cat_id_$i"];
	$i--;
      }
    return 0;
  }
  /* unset 以下类别，设置cat_id
   * cat_id_0, cat_id_1, cat_id_2, cat_id_3, cat_id_4
   */
  public function setLastCatId(&$post, $cat_id)
  {
    $i = 4;
    while ($i >= 0)
      {
	if (isset($_POST["cat_id_$i"]))
	  unset($_POST["cat_id_$i"]);
	$i--;
      }
    $_POST["cat_id"] = $cat_id;
    
  }

  public function getCategoryTree($cat_id, $prefix="")
  {
    $res = $this->getCategoryList($cat_id);

    // $str = "";
    $cats = array();
    foreach($res as $id=>$name)
      {
	//$str .= $prefix . $name . "<br/>" . $this->getCategoryTree($id, $prefix."..");
	$cats[] = array("detail"=>array($id=>$name), "children" => $this->getCategoryTree($id));
      }

    return $cats;
  }
}